package com.powernode.usermgt.dao;

import com.powernode.usermgt.bean.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 曾铖坚
 * @Date: 2024/10/4 17:53
 * @Version: 1.0.0
 */
@Repository
public class UserDao {
    private static List<User> users = new ArrayList<>();

    static {
        User user1 = new User(1001L,"张三",1,"zhangsan@qq.com");
        User user2 = new User(1002L,"孙悟空",1,"wukong@qq.com");
        User user3 = new User(1003L,"猪八戒",1,"bajie@qq.com");
        User user4 = new User(1004L,"白骨精",0,"bgj@qq.com");
        User user5 = new User(1005L,"沙和尚",1,"heshang@qq.com");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);
    }

    /**
     * 从数据库中查询用户信息
     * @return 用户列表
     */
    public List<User> selectALL(){
        return users;
    }

    /**
     * 专门生成id的
     * @return
     */
    public Long generate(){
        // Stream API
        Long maxId = users.stream().map(user -> user.getId()).reduce((id1, id2) -> id1 > id2 ? id1 : id2).get();
        return maxId + 1;
    }

    /**
     * 保存用户信息
     * @param user
     */
    public void insert(User user){
        // 生成id
        Long id = generate();
        // 给user的id属性赋值
        user.setId(id);
        // 添加到集合中
        users.add(user);
    }

    /**
     * 根据用户id查找用户信息
     * @param id
     * @return
     */
    public User selectById(Long id){
        // stream API
        return users.stream().filter(user -> user.getId().equals(id)).findFirst().get();
    }

    /**
     * 修改用户信息
     * @param user
     */
    public void update(User user){
        for (int i = 0; i < users.size(); i++) {
            if(users.get(i).getId().equals(user.getId())){
                users.set(i,user);
                return;
            }
        }
    }

    /**
     * 根据id删除用户信息
     * @param id
     */
    public void deleteById(Long id){
        for (int i = 0; i < users.size(); i++) {
            if(users.get(i).getId().equals(id)){
                users.remove(i);
                return;
            }
        }
    }
}
